import { fetchApplicationInfo } from "@/services/robotManagement";
import { postAssistantEdit } from "@/services/digitalEmployees";
import jsonDataUtils from "@/utils/jsonDataUtils";
import { Form, Tag, Input, Radio, Button, message, Tooltip, Icon, Upload } from "antd";
import React from "react";
import styles from "./robotAdd.less";
import UserSession from "@/UserSession";
import { formatMessage } from 'umi-plugin-react/locale';

class BasicSetting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      applicationInfo: {},
      
      avatar: "",
      loading: false,
    }
  }

  componentDidMount() {
    this.getApplicationInfo()
  }

  getApplicationInfo = async () => {
    const { applicationId, channel } = this.props;
    const res = await fetchApplicationInfo({ id: applicationId })
    this.setState({ applicationInfo: res, avatar: res.imagUrl }, () => {
      this.props.form.setFieldsValue({
        applicationName: res.name,
        introduction: res.introduction,
        avatar: res.imagUrl,
      });
    })
  }

  doSaveApplicationInfo = () => {
    const that = this;
    const { avatar } = this.state;
    const { applicationId } = this.props;
    that.props.form.validateFieldsAndScroll(async (err, values) => {
      if (!err) {
        let obj = { name: values.applicationName, id: applicationId, introduction: values.introduction };
        if (avatar && avatar !== '') {
          obj.imgUrl = avatar;
        } else {
          form.setFields({ avatar: { errors: [new Error('指令图片必填')], } });
          return;
        };
        let res = await postAssistantEdit(obj);
        message.info(res.message);
        that.getApplicationInfo();
      }
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { applicationInfo, avatar } = this.state;
    const uploadButton = (
      <div style={{ border: '#E8E8E8 1px solid', padding: '14px 7px', textAlign: 'center', background: '#FAFAFA', }}>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">{formatMessage({ id: 'digitalEmployees.basicSetting.uploadFile' })}</div>
      </div>
    );

    return (
      <div>
        <Form layout="vertical" style={{ width: '75%' }}>
          <Form.Item label={formatMessage({ id: 'digitalEmployees.basicSetting.aiConsultantName' })}>
            {getFieldDecorator("applicationName", { rules: [{ required: true, message: formatMessage({ id: 'digitalEmployees.basicSetting.required.aiConsultantName' }) }] })(<Input maxLength={20} />)}
          </Form.Item>
          <div style={{ display: 'flex', width: '100%', gap: '16px' }}>
            <Form.Item label={formatMessage({ id: 'digitalEmployees.basicSetting.aiConsultantIntro' })} style={{ flex: 1, marginBottom: 16 }}>
              {getFieldDecorator('introduction', { rules: [{ required: true, message: formatMessage({ id: 'digitalEmployees.basicSetting.required.aiConsultantIntro' }) }], })(<Input.TextArea rows={3} placeholder={formatMessage({ id: 'digitalEmployees.basicSetting.placeholder.aiConsultantIntro' })} />)}
            </Form.Item>
            <Form.Item label={formatMessage({ id: 'digitalEmployees.basicSetting.avatar' })} style={{ marginBottom: 16 }}>
              <span className={styles['default-img-ul']}>
                {getFieldDecorator("avatar", {
                  initialValue: applicationInfo?.imagUrl,
                  valuePropName: "url",
                  rules: [{ required: true }],
                  getValueFromEvent: this.normFile,
                })(
                  <Upload
                    name='file'
                    listType='picture'
                    showUploadList={false}
                    action='/cloud/file/upload'
                    beforeUpload={this.beforeUpload}
                    onChange={(info) => this.handleChangeImage(info, "avatar")}
                    accept='.png,.jpg,.gif,.svg'
                  >
                    {avatar && avatar !== '' ? (
                      <div
                        style={{
                          width: '72px',
                          height: '72px',
                          fontSize: '0px',
                          lineHeight: '72px',
                          textAlign: 'center',
                          border: '#3e5bff 1px solid',
                          background: '#f0f5ff',
                        }}
                      >
                        <img src={fileUrl + avatar} alt='file' style={{ maxWidth: 70, maxHeight: 70 }} />
                      </div>
                    ) : uploadButton}
                  </Upload>
                )}
              </span>
            </Form.Item>
          </div>
          <Form.Item colon={false} label={<Button type="primary" onClick={this.doSaveApplicationInfo}>{formatMessage({ id: 'digitalEmployees.basicSetting.save' })}</Button>}></Form.Item>
        </Form>
      </div>
    )
  }
  
  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  handleChangeImage = (file, type) => {
    if (file.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    };
    if (file.file.status === "done") {
      this.setState({
        [type]: file.file.response.url,
        loading: false,
      });
    }
  };

  /**
   * 上传图片前判断
   * @returns {*}
   */
  beforeUpload = (file) => {
    let b = /\.(png|jpg|gif|svg)$/;
    let a = file.name.toLowerCase();

    const pig = b.test(a);
    const isJPG = file.type;
    const isLt2M = file.size / 1024 / 1024 < 200;

    if (!pig) {
      if (!isLt2M) {
        message.error(formatMessage({ id: 'digitalEmployees.basicSetting.error.imageSize' }))
      } else {
        message.error(formatMessage({ id: 'digitalEmployees.basicSetting.error.imageFormat' }))
      }
    } else {
      if (!isLt2M) {
        message.error("请上传小于2M的图片");
      }
    };
    return isJPG && isLt2M && pig;
  };

  setImgUrl = (row, type) => {
    this.setState({ [type]: row.url });
  }
}

export default Form.create()(BasicSetting)